/**
 * fulihui.com Inc.
 * Copyright (c) 2015-2016 All Rights Reserved.
 */
package com.fulihui.integral.core.strategy;

import com.fulihui.integral.core.common.entity.RuleData;
import com.fulihui.integral.core.common.utils.ISRuleParseUtil;
import com.fulihui.integral.core.dal.dataobj.ISRuleInfo;
import com.fulihui.integral.core.dal.dataobj.ISRuleInfoExample;
import com.fulihui.integral.core.dal.mapper.ISRuleInfoMapper;
import com.fulihui.integral.core.enums.ISChannelType;
import com.fulihui.integral.core.enums.ISRuleSwitchType;
import org.near.toolkit.common.StringUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 策略器上下文
 *
 * @author yunfeng.li
 * @version $Id: v 0.1 2017年04月19日 19:29 yunfeng.li Exp $
 */
@Component
public class RewardContext {

    @Resource
    private StrategyFactory strategyFactory;

    private BaseStrategy strategy;

    @Resource
    private ISRuleInfoMapper iSRuleInfoMapper;

    public StrategyResult calculate(StrategyParam param) {
        String channel = param.getChannel();
        StrategyResult result = new StrategyResult();
        //如果是分享渠道
        if (!StringUtil.equals(ISChannelType.FIRST_SHARE.getCode(), channel)) {
            //规则检验
            ISRuleInfoExample example = new ISRuleInfoExample();
            ISRuleInfoExample.Criteria criteria = example.createCriteria();
            criteria.andChannelEqualTo(channel);
            List<ISRuleInfo> isRuleInfos = iSRuleInfoMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(isRuleInfos)) {
                return result;
            }
            ISRuleInfo isRuleInfo = isRuleInfos.get(0);
            String ruleSwitch = isRuleInfo.getRuleSwitch();
            if (StringUtil.equals(ISRuleSwitchType.OFF.getCode(), ruleSwitch)) {
                return result;
            }
            String ruleTemplate = isRuleInfo.getRuleTemplate();
            if (StringUtil.isNotBlank(ruleTemplate)) {
                Map<String, RuleData> ruleDataMap = ISRuleParseUtil.toMap(ruleTemplate);
                param.setRule(ruleDataMap);
            } else {
                return result;
            }
        }
        strategy = strategyFactory.creator(channel);
        return strategy.calculate(param);
    }

}
